package com.redwood.report.activity.mvp.login;

import android.app.Activity;
import android.text.TextUtils;

import com.redwood.report.common.Config;
import com.redwood.report.entity.ServiceResult;
import com.redwood.report.entity.bak.UserInfo;
import com.redwood.report.entity.bak.been.User;
import com.redwood.report.net.Api;
import com.redwood.report.net.NetUtils;
import com.redwood.report.observer.ReadSmsObserver;


/**
 * Created by Supeng on 2018/8/16.
 */

public class LoginPresenter {
    private LoginView loginView;
    private Activity context;
    private ReadSmsObserver mReadSmsObserver;
    private String tipsNameNone="用户名不能为空";
    private String tipsPsdNone="密码不能为空";
    private String tipsipNone="IP地址不能为空";
    LoginPresenter(LoginView loginView,Activity context){
        this.loginView=loginView;
        this.context=context;
    }

    //释放引用
    public void onDestroy(){
        if (mReadSmsObserver != null) {
            context.getContentResolver().unregisterContentObserver(mReadSmsObserver);
            mReadSmsObserver = null;
        }
        context=null;
        loginView=null;
    }
    //登录
    public void login(String username,String psd){
        if(TextUtils.isEmpty(username)){
            loginView.tips(tipsNameNone);
            return;
        }
        if(TextUtils.isEmpty(psd)){
            loginView.tips(tipsPsdNone);
            return;
        }
        Api.login(context, username, psd, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getRecode()==1) {
                    UserInfo userInfo= (UserInfo) rspData;
                    User user=userInfo.getInfo();
                    Config.setUserInfo(user);
                    if(loginView!=null)
                        loginView.loginSuccess();
                }else{
                    if(loginView!=null)
                        loginView.loginFail();
                }
            }

            @Override
            public void failed(String msg) {
                if(loginView!=null)
                    loginView.loginFail();
            }

            @Override
            public void onUsedCache(String msg) {

            }
        },UserInfo.class);
    }
}
